import { AlertManager } from "../alert/AlertManager";
import { Notifier } from "../framework/Notifier";
import GlobalData from "../GlobalData";
import { ListenID } from "../ListenID";
import CaptureUtils from "../utils/Capture";
import { Util } from "../utils/Util";
import DeviceManager from "./DeviceManager";

export default class KuaishouManager {

    private static _instance: KuaishouManager = null;
    public static get inst(): KuaishouManager {
        return this._instance || (this._instance = new KuaishouManager());
    }

    constructor() {
    }

    login(ret: ({ login, userInfo }) => void, err?: Function) {
        if (Util.isKuaishouGame()) {
            ks.authorize({  
                scope: "scope.userInfo",  
                success: () => {  
                    console.log("授权获取用户信息成功");  
                },  
                fail: (error) => {  
                    console.log("授权获取用户信息失败: " + JSON.stringify(error));  
                },  
                complete:() => {  
                    console.log("授权获取用户信息完成");  
                }  
            });  
            ks.login({
                success(_res) {
                    console.log("登录成功");
                    // 调用getUserInfo前, 请确保登录成功
                    // 获取用户信息
                    ks.getUserInfo({
                        success(res) {
                            console.log(`ks getUserInfo 调用成功`, res);

                            ret && ret({
                                login: _res,
                                userInfo: res.userInfo || {}
                            })
                        },
                        fail(res) {
                            console.log(`getUserInfo 调用失败`, res.errMsg);
                            ret && ret({
                                login: _res,
                                userInfo: res.userInfo
                            })
                        },
                    });
                },
                fail(res) {
                    console.log(`login 调用失败`);
                },
            });
        }
    }

    private videoAd;
    private interstitialAd;
    private adInitVideoAd(){
        if(!Util.isKuaishouGame()){
            return;
        }
        this.videoAd = null;
        let param : any = {};  
        param.adUnitId = "2300022055_01";     
        this.videoAd = ks.createRewardedVideoAd(param);
    }
    private adInitInterstitialAd(){
        console.log("adInitInterstitialAd");
        let param : any = {};  
        param.adUnitId = "2300022055_02";          
        if(this.interstitialAd){
            this.interstitialAd.destroy().then(()=>{
                console.log("插屏广告销毁成功");
                this.interstitialAd = ks.createInterstitialAd(param);

            })
            return;
        }
        
        this.interstitialAd = ks.createInterstitialAd(param);
    }
    adinit() {
        if(!Util.isKuaishouGame()){
            return;
        }
        this.adInitVideoAd();
        this.adInitInterstitialAd();
    }

    playReward(callback: Function) {
        console.log("playReward");
        if(!Util.isKuaishouGame()){
            return;
        }

        this.videoAd.onError(res => {
            // 激励视频广告Error事件
            console.log("激励视频广告Error事件",res);
          })
        this.videoAd
                .show()
                .then(() => {
                    console.log("广告显示成功");
                })
                .catch((err) => {
                    console.log("广告组件出现问题", err);
                });

            let listener = (res) => {
                console.log("广告关闭", res);
                // 用户点击了【关闭广告】按钮 
                this.videoAd.offClose(listener);
                if (res && res.isEnded) {  
                    // 正常播放结束，可以下发游戏奖励 
                    if (res.count) {
                        //在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
                        //判断观看了几次广告
                    }
                    callback("ok");
                } else {
                    // 播放中途退出，不下发游戏奖励 
                    callback("err");
                }
             
        }

        this.videoAd.onClose(listener); //这里监听广告的close 事件
    }
    // 不提前加载播放激励广告
    playRewardNoLoad(callback: Function) {
        if (Util.isKuaishouGame()) {
            this.playReward(callback);
        }
    }

    share(uid) {
        if (Util.isKuaishouGame()) {
            ks.shareAppMessage({
                query: "uid=" + uid,
                success() {
                    console.log("分享成功");
                },
                fail(e) {
                    console.log("分享失败");
                },
            });
        }
    }

    shareAndroid(shareNode: cc.Node, showLoader?: cc.Sprite) {
        let capture = CaptureUtils.capture(shareNode);
        if (cc.isValid(showLoader)) {
            showLoader.spriteFrame = capture[0];
        }

        if (!jsb || !DeviceManager.inst.isAndroid) return;

        let url = CaptureUtils.toImgUrl(capture[1]);
        console.log("存储的地址", url);
        setTimeout(() => {
            jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "DYShareImage", "(Ljava/lang/String;)V", url);

        }, 1000);
    }

    shareUrlAndroid(url: string) {
        jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "DYShareUrl", "(Ljava/lang/String;)V", url);
    }

    getLocation(successCallback: Function, failCallback?: Function) {
        if (Util.isKuaishouGame()) {
            ks.getLocation({
                success(res) {
                    console.log(`经度${res.longitude}，维度${res.latitude}`);
                    successCallback && successCallback(res);
                },
                fail(res) {
                    console.log(`getLocation调用失败`);
                    failCallback && failCallback();
                },
            });

        }
    }
    playCreateInterstitialAd(){
        console.log("playCreateInterstitialAd"); 
        if(Util.isKuaishouGame()){
            if (this.interstitialAd) {  
                this.interstitialAd.onClose(res => {  
                    // 插屏广告关闭事件  
                    console.log("插屏广告关闭",res);
                })  
                this.interstitialAd.onError(err => {  
                    // 插屏广告Error事件  
                    console.log("插屏广告加载失败",err);
                })  
                let p = this.interstitialAd.show()  
                p.then(function(result){  
                    // 插屏广告展示成功  
                    console.log("插屏广告展示成功, result",result)  
                }).catch(function(error){  
                    // 插屏广告展示失败  
                    console.log("插屏广告展示失败, error",error)  
                    if (error.code === -10005) {  
                        // 表明当前app版本不支持插屏广告，可以提醒用户升级app版本  
                        AlertManager.showNormalTips("当前app版本不支持插屏广告，请升级app版本");
                    }  
                })  
            } else {  
                   console.log("创建插屏广告组件失败");  
            } 

        }
    }

}